<script>
import * as IncreaseUtil from '@/components/util/IncreaseUtil'
export default {
  data() {
    return {
      selectedSubject: {},
      selectedEnergyId: null,
      energyInfo: {data:[], view: []},
      selectedTimeRange: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7), new Date()],
      treeData: [],
      itemList: [],
      queryResultInfo: [
        {
          param:{},
          list: {}
        }
      ],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      pieChartOption: {
        tooltip: {
          trigger: 'item',
          formatter: function (c) {
            return '对比序列：' + c.data.name + '<br>能耗：' + c.data.value + ' kgce' + '<br>占比：' + c.percent + '%';
          }
        },
        series: [
          {
            type: 'pie',
            data: []
          }
        ]
      },
      lineChartOption: {
        grid: {
          left: '2%',
          right: '2%',
          bottom: '2%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (c) {
            return '时间：' + c[0].name + '<br>能耗：' + c[0].value + ' kgce';
          }
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          },
        },
        series: []
      }
    };
  },
  mounted() {
    this.fetchTreeData()
    this.fetchBaseList()
    this.queryResultInfo = []
  },
  methods: {
    queryData: function () {
      this.fetchData()
    },
    clearAll: function () {
      this.queryResultInfo = []
      this.initLineChart()
      this.initPieChart()
    },
    fetchTreeData: function () {
      const data = {content: {excludeTypes:["METER","POINT","GATEWAY"]}}
      this.$axios({url:'/ems/client/energy/search/subject/tree',data: data}).then((content) => {
        this.treeData = content.list
      });
    },
    initPieChart: function () {
      const array = this.queryResultInfo;
      const dataArr = []
      let showTypeKey = 'increaseStandValue'
      this.pieChartOption.series[0].data = []
      for (let m = 0; m < array.length; m ++) {
        let sumVal = 0
        for (let i = 0; i < array[m].list.length; i ++) {
          const item = array[m].list[i]
          sumVal = sumVal + item['' + showTypeKey + '']
        }
        dataArr.push({value: this.$doubleVal(sumVal), name: m})
      }
      this.pieChartOption.series[0].data = dataArr;
      this.$nextTick(() => {
        const chart = this.$echarts.init(this.$refs.pieChart)
        chart.setOption(this.pieChartOption)
      })
    },
    initLineChart: function () {
      let showTypeKey = 'increaseStandValue'
      this.lineChartOption.xAxis.data = [];
      this.lineChartOption.series = [];
      const array = this.queryResultInfo;
      for (let m = 0; m < array.length; m ++) {
        const seriesData = {type: 'line',data: []}
        for (let i = 0; i < array[m].list.length; i ++) {
          const item = array[m].list[i]
          if (m === 0) {
            this.lineChartOption.xAxis.data.push(item.time);
          }
          seriesData.data.push(this.$doubleVal(item['' + showTypeKey + '']));
        }
        this.lineChartOption.series.push(seriesData)
      }
      this.$nextTick(() => {
        this.chart = this.$echarts.init(this.$refs.lineChart)
        this.chart.setOption(this.lineChartOption)
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    fetchBaseList: function () {
      const data = {content: {}}
      this.$axios({url:'/ems/client/base/energy/list',data: data}).then((content) => {
        const list = content.list;
        list.forEach(function (item) {
          if (item.nameInfo) {
            item.nameInfo = JSON.parse(item.nameInfo)
          }
        })
        this.energyInfo.data = list
        this.energyInfo.view = list
      });
    },
    fetchData: function () {
      let fromDate = null
      let toDate = null
      let showType = 'hour'
      if (this.selectedTimeRange.length === 2) {
        const s = this.$getTimeInfo(this.selectedTimeRange[0]);
        const e = this.$getTimeInfo(this.selectedTimeRange[1])
        const dis = this.selectedTimeRange[1].getTime() - this.selectedTimeRange[0].getTime()
        if (dis > 1000 * 60 * 60 * 24) {
          showType = 'day'
        }
        fromDate = s.year + '-' + s.month + '-' + s.day + ' 00:00:00';
        toDate = e.year + '-' + e.month + '-' + e.day + ' 23:59:59';
      }
      const data =
          {
            content: {
              subjectId:this.selectedSubject.id,
              selectedSubject: this.selectedSubject,
              subjectType: this.selectedSubject.type,
              energyId: this.selectedEnergyId,
              energyObj: {id: this.selectedEnergyId, name: IncreaseUtil.getJsonArrValueByField(this.energyInfo.data, 'id', this.selectedEnergyId, 'nameInfo')},
              paramIndex: this.queryResultInfo.length,
              fromDate: fromDate,
              toDate: toDate,
              toDateType: showType
            }
          }
      this.$axios({url:'/ems/client/index/energy/time/trend',data: data}).then((content) => {
        const list = content.list
        this.queryResultInfo.push({
          param: data,
          list: list
        })
        this.initLineChart()
        this.initPieChart()
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    treeClick: function (item) {
      this.dialogVisible = false
      this.selectedSubject = item
    }
  }
};
</script>

<template>
  <div>
    <el-row>
      <el-col :span="24" style="height: 50px;">
        <label style="margin-left: 1%;">主体：</label>
        <el-button type="text" @click="dialogVisible = true"
                   style="background-color: white;width: 350px;color: rgb(192, 196, 204);">
          {{ !selectedSubject.label ? '请选择用能主体' : selectedSubject.label }}
        </el-button>
        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose">
          <el-tree
              class="filter-tree"
              :data="treeData"
              :props="defaultProps"
              :filter-node-method="filterNode"
              @node-click="treeClick"
              ref="tree">
          </el-tree>
        </el-dialog>&nbsp;
        能源分类：
        <el-select v-model="selectedEnergyId" placeholder="请选择能源类型">
          <el-option
              v-for="item in energyInfo.view"
              :key="item.id"
              :label="item.nameInfo['zh-CN']"
              :value="item.id">
          </el-option>
        </el-select>&nbsp;
        时间范围：<el-date-picker
            v-model="selectedTimeRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
        </el-date-picker>&nbsp;
        <el-button primary @click="queryData" type="primary" plain>加入对比</el-button>
        <el-button @click="clearAll" style="margin-right: 24%;" type="primary" plain>清除所有</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
            :data="queryResultInfo"
            style="width: 100%;margin-left: 1%;">
          <el-table-column
              prop="param.content.paramIndex"
              label="对比序列"
              align="center"
              width="180">
          </el-table-column>
          <el-table-column
              prop="param.content.selectedSubject.label"
              label="主体"
              align="center"
              width="280">
          </el-table-column>
          <el-table-column prop="param.content.energyObj.name['zh-CN']" label="分类名称" align="center">
            <template scope="scope">
              {{ scope.row.param.content.energyObj.name['zh-CN'] }}
            </template>
          </el-table-column>
          <el-table-column
              prop="param.content.fromDate"
              align="center"
              label="开始时间">
          </el-table-column>
          <el-table-column
              prop="param.content.toDate"
              align="center"
              label="结束时间">
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="18">
        <div ref="lineChart" style="height: 500px;"></div>
      </el-col>
      <el-col :span="6">
        <div ref="pieChart" style="height: 500px;"></div>
      </el-col>
    </el-row>
  </div>
</template>

<style>

</style>
